import UserModel from "~/models/UserModel";
import argon2 from 'argon2';
import jwt from 'jsonwebtoken';

export const signin = async (name: string, pass: string) => {
    const user = await UserModel.findOne({ username: name });
    if (!user) throw 'User not found!';

    if (!await argon2.verify(user.password!, pass)) throw 'Password not match!';

    // 生成token
    const time = +new Date();
    const token = jwt.sign({ _id: user._id, time }, process.env.JWT_KEY as string, { expiresIn: 7 * 24 * 60 * 60 });

    // 更新登入时间
    await UserModel.findByIdAndUpdate(user._id, { signin_time: `${time}` });

    return { token };
};

export const signup = async (name: string, pass: string) => {
    // 验证唯一性
    if (((await UserModel.find({ username: name })).length)) throw 'This name has been used!';

    // 注册账号
    const time = +new Date();
    const password = await argon2.hash(pass);
    const user = await UserModel.create({ username: name, password, signup_time: time });

    return user;
};

export const getProfile = async (userId: string) => {
    const profile = await UserModel.findById(userId, {
        _id: 0,
        username: 1,
        avatar: 1,
        balance: 1,
    });
    if (!profile) throw 'Profile not found!';

    return profile;
};